package top.lingkang.mm.orm;

import top.lingkang.mm.utils.MapParam;

import java.util.HashMap;
import java.util.Map;

/**
 * 更新包装对象，例1 ：
 * <pre>
 * {@code
 *     UpdateWrapper update = mapperManage.createUpdate("update t_user set password=#{p} where id=#{id}");
 *     update.addParam("p", System.currentTimeMillis()).addParam("id", 1);
 *     int execute = update.execute();
 *     log.info("受影响行数: {}", execute);
 * }
 * </pre>
 * 例2：
 * <pre>
 * {@code
 *     UpdateWrapper update = mapperManage.createUpdate("insert into t_user(id,username) values (2,#{un})");
 *     update.addParam("un", "lk");
 *     int execute = update.execute();
 *     log.info("受影响行数: {}", execute);
 * }
 * </pre>
 *
 * @author lingkang
 * @create by 2024/3/6
 */
public class UpdateWrapper extends MapParam {
    private String sql;
    private MapperManageImpl manage;

    public UpdateWrapper(String sql, MapperManageImpl manage) {
        this.sql = sql;
        this.manage = manage;
    }

    /**
     * 添加参数，sql中的参数只能用 #{paramName} <br>
     * 代码例子：
     * <pre>
     * {@code
     *     UpdateWrapper update = mapperManage.createUpdate("update t_user set password=#{p} where id=#{id}");
     *     update.addParam("p", System.currentTimeMillis()).addParam("id", 1);
     *     int execute = update.execute();
     *     log.info("受影响行数: {}", execute);
     * }
     * </pre>
     *
     * @param name  参数名
     * @param value 参数值
     * @return 查询包装对象
     */
    public UpdateWrapper addParam(String name, Object value) {
        super.put(name, value);
        return this;
    }

    /**
     * 添加 map 参数
     * <pre>
     * {@code
     *         Map<String, Object> map = new HashMap<>();
     *         map.put("id", 123);
     *         int execute = mapperManage.createUpdate("insert into t_user(id) values(#{id});")
     *                 .addParam(map)
     *                 .execute();
     *         System.out.println(execute);
     *         UserMapper mapper = mapperManage.getMapper(UserMapper.class);
     *         System.out.println(mapper.selectColumn(new QueryColumn(String.class, "id")));
     * }
     * </pre>
     *
     * @param params map参数
     * @return 查询包装对象
     */
    public UpdateWrapper addParam(Map<String, Object> params) {
        super.putAll(params);
        return this;
    }

    /**
     * 执行更新操作
     *
     * @return 受影响行数
     */
    public int execute() {
        super.put("execSql_", sql);
        return manage.langMapper.update(this);
    }

}
